package com.lxq.LeetCode.threeSum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[] nums = {0,0,0};
        List<List<Integer>> res = threeSum(nums);
        System.out.println(res);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
        for (int i = 0; i < nums.length - 2; i++) {
            int p1 = i + 1, p2 = nums.length - 1;
            while (p1 < p2) {
                if (nums[p1] + nums[p2] == -nums[i]) {
                    List<Integer> tempList = new ArrayList<>();
                    tempList.add(nums[i]);
                    tempList.add(nums[p1]);
                    tempList.add(nums[p2]);
                    res.add(tempList);
                    do {
                        p1++;
                        p2--;
                    } while (p1<p2&& nums[p1] == nums[p1 - 1]&& nums[p2] == nums[p2 + 1]);

                } else {
                    if (nums[p1] + nums[p2] < -nums[i]) {
                        p1++;
                    } else {
                        p2--;
                    }
                }
            }
            while (i<nums.length-1&&nums[i + 1] == nums[i]) {
                i++;
            }
        }
        return res;
    }

}
